package com.adlotto2.lcdns.activity.info;

import java.util.ArrayList;

import org.w3c.dom.Element;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adlotto2.lcdns.R;
import com.adlotto2.lcdns.activity.info.adapter.LottoAdAdressAdapter;
import com.adlotto2.lcdns.common.BaseActivity;
import com.adlotto2.lcdns.cronos.data.CNLottoAdAdressData;
import com.adlotto2.lcdns.cronos.datahandler.CNBaseDataParser;
import com.adlotto2.lcdns.cronos.datahandler.CNBaseDataSet;
import com.adlotto2.lcdns.cronos.datahandler.CNResultSet;
import com.adlotto2.lcdns.cronos.http.CNLottoAdApiSetEx;
import com.adlotto2.lcdns.cronos.parser.CNZipcodListParser;
import com.adlotto2.lcdns.util.ApplicationUtils;
import com.adlotto2.lcdns.util.CNCronosLog;

/**
 * 상세주소 목록 Activity
 * @author Administrator
 *
 */
public class LottoAdAdressListActivity extends BaseActivity {

	private Context mContext;
	
	/**주소 구분 인덱스 값**/
	private final int INDEX_ACTIVITY_SIDO = 0;
	private final int INDEX_ACTIVITY_GUGUN = 1;
	private final int INDEX_ACTIVITY_DONG = 2;
	private int mCurrentIndex = -1;
	
	/**주소 GridView**/
	private GridView mAdressGrid;
	/**주소 Adapter**/
	private LottoAdAdressAdapter mAdressAdapter;
	/**주소 DataSetList**/
	private ArrayList<CNBaseDataSet> mAdressDataSetList = null;
	
	/**각 주소 String 값**/
	private String mSido = null;
	private String mGugun = null;
	private String mDong = null;
	
	private ImageView mTitleImage;
	
	// 백그라운드 레이아웃
	private LinearLayout mBaseLayout;
	
	private Handler mHandler;
	
	private boolean mIsFromRegistActivity = true;
	
	private int mSearchLimit = -1;
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_info_adress_list;
	}

	@Override
	protected void onInit() {
		String extra = "";
		extra = getIntent().getStringExtra("isRegistActivity");
		if(extra != null) {
			if(extra.equals("false")) {
				mIsFromRegistActivity = false;
				mSearchLimit = getIntent().getIntExtra("searchLimit", 1);
			}
		} else {
		}
		buildComponnent();
	}
	
	protected void buildComponnent() {
		this.mContext = this;
		
		mBaseLayout = (LinearLayout) findViewById(R.id.ll_service_local);
		
		if(!mIsFromRegistActivity) {
			mBaseLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.basic_bg));
		}
		
		mHandler = new Handler();
		
		setContentView(R.layout.lottoad_info_adress_list);
		
		mAdressGrid = (GridView) findViewById(R.id.gridView_adress);
		mTitleImage = (ImageView) findViewById(R.id.type_address);
		
		mAdressAdapter = new LottoAdAdressAdapter(mContext);
		mAdressGrid.setAdapter(mAdressAdapter);
		mAdressGrid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,	int position, long l) {
				switch(mCurrentIndex){
					case INDEX_ACTIVITY_SIDO:
						mSido = ((TextView)view.findViewById(R.id.textView_adress)).getText().toString();
						if(mSearchLimit == INDEX_ACTIVITY_SIDO) {
							Intent intent = new Intent();
							intent.putExtra("address", mSido);
							intent.putExtra("sido", mSido);
							setResult(RESULT_OK,intent);
							finish();
						} else {
							onRequestData();
						}
						break;
					case INDEX_ACTIVITY_GUGUN :
						mGugun = ((TextView)view.findViewById(R.id.textView_adress)).getText().toString();
						if(mSearchLimit == INDEX_ACTIVITY_GUGUN) {
							Intent intent = new Intent();
							intent.putExtra("address", mSido + " " + mGugun);
							intent.putExtra("sido", mSido);
							intent.putExtra("gugun", mGugun);
							setResult(RESULT_OK,intent);
							finish();
						} else {
							onRequestData();
						}
						break;
					case INDEX_ACTIVITY_DONG :
						mDong = ((TextView)view.findViewById(R.id.textView_adress)).getText().toString();
						Intent intent = new Intent();
						intent.putExtra("address", mSido+" "+mGugun+" "+mDong);
						intent.putExtra("sido", mSido);
						intent.putExtra("gugun", mGugun);
						intent.putExtra("dong", mDong);
						setResult(RESULT_OK,intent);
						finish();
						break;
				}
			}
		});
		
		onRequestData();
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		switch(mCurrentIndex){
			case -1:
				url = MnetGlobalApiSetEx.getSidoListUrl(mContext);
			break;
			case INDEX_ACTIVITY_SIDO :
				url = MnetGlobalApiSetEx.getGugunListUrl(mContext, mSido);
				break;
			case INDEX_ACTIVITY_GUGUN :
				url = MnetGlobalApiSetEx.getDongListUrl(mContext, mSido, mGugun);
				break;
		}
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext, 0, "알림", errorMessage);
	}

	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog();
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
		
		try {
			mHandler.post(new parsingThread(xmlObject));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}
	
	public class parsingThread implements Runnable{
		
		private Element mXmlObject;
		
		public parsingThread(Element xmlObject){
			this.mXmlObject = xmlObject;
		}

		@Override
		public void run() {
			try {
				parseAddressList(mXmlObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 각 인덱스에 따른 주소값 파싱
	 * @param xmlObject : XmlObject
	 * @throws Exception
	 */
	private void parseAddressList(Element xmlObject) throws Exception
	{
		
		mAdressDataSetList = new ArrayList<CNBaseDataSet>();
		
		String Tag = "parseAddressList";
		
		CNBaseDataParser parser = new CNZipcodListParser();
		CNResultSet resultSet = parser.parse(xmlObject);
		ArrayList<CNBaseDataSet> dataSet = null;
		
		if (resultSet != null)
		{
			dataSet = resultSet.getDataSetList();
			if (dataSet != null)
			{
				int count = dataSet.size();		
				CNCronosLog.d(Tag, "DataSet.size():" + count);
				for (int i = 0; i < count; i++)
				{
					CNLottoAdAdressData data = (CNLottoAdAdressData) dataSet.get(i);
					
					CNCronosLog.d("============ " + i + " ============");
					CNCronosLog.d( "adressSIDO:" + data.adressSIDO);
					CNCronosLog.d("adressGUGUN:" + data.adressGUGUN);
					CNCronosLog.d("adressDONG:" + data.adressDONG);
					
					mAdressDataSetList.add(data);
				}
			}
			mAdressAdapter.setDataSetList(mAdressDataSetList);
			mAdressAdapter.notifyDataSetChanged();
			
			switch(mCurrentIndex){
			case -1:
				mCurrentIndex = INDEX_ACTIVITY_SIDO;
			break;
			case INDEX_ACTIVITY_SIDO :
				mTitleImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.service_title_local_borough));
				mCurrentIndex = INDEX_ACTIVITY_GUGUN;
				break;
			case INDEX_ACTIVITY_GUGUN :
				mTitleImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.service_title_local_town));
				mCurrentIndex = INDEX_ACTIVITY_DONG;
				break;
			}
		}
	}
	
	@Override
	public void onBackPressed() {
		switch(mCurrentIndex){
			case INDEX_ACTIVITY_SIDO :
				finish();
				break;
			case INDEX_ACTIVITY_GUGUN :
				mTitleImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.service_title_local_city));
				mCurrentIndex = -1;
				onRequestData();
				break;
			case INDEX_ACTIVITY_DONG :
				mTitleImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.service_title_local_borough));
				mCurrentIndex = INDEX_ACTIVITY_SIDO;
				onRequestData();
				break;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mAdressAdapter.recycle();
	}
}
